package com.wing.warehouse.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.platform.feign.PlatformClient;
import com.wing.product.model.response.WarehouseProductVO;
import com.wing.warehouse.model.entity.Warehouse;
import com.wing.warehouse.model.entity.WarehouseFactoryAdministrationVO;
import com.wing.warehouse.model.entity.WarehouseFactoryShelfSpaceVO;
import com.wing.warehouse.model.entity.WrehouseFactoryAdministrationEntity;
import com.wing.warehouse.model.request.WarehouseFactoryAdministrationForm;
import com.wing.warehouse.controller.admin.service.WarehouseFactoryAdministrationService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.db.config.util.DynamicDataSource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Validated
@Api(value = "Admin-仓库管理", tags = "#/warehouseFactory/warehouseFactoryAdministration")
@RestController("WarehouseFactoryAdministrationController")
@RequestMapping("warehouse/admin/administration")
@RequiredArgsConstructor
public class WarehouseFactoryAdministrationController {

    private final WarehouseFactoryAdministrationService warehouseService;
    @Autowired
    private PlatformClient platformClient;

    @ApiOperation(value = "查询所有仓库", notes = "搜索")
    @GetMapping("/list")
    public PageResult<WarehouseFactoryAdministrationVO> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "999") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String name,
            String code,
            Long warehouseTypeId,
            Long productTypeId) {
        Page pg = new Page(page, limit);
        Map queryParam = new HashMap();
        queryParam.put("sort", StrUtil.toUnderlineCase(sort));
        queryParam.put("order", order);
        queryParam.put("name", name);
        queryParam.put("code", code);
        if (null != productTypeId) {
            queryParam.put("productTypeId", productTypeId);
        }
        if (null != warehouseTypeId) {
            queryParam.put("warehouseTypeId", warehouseTypeId);
        }
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        queryParam.put("databaseUser", databaseUser);
        IPage<WarehouseFactoryAdministrationVO> list = warehouseService.pageList4app(pg, queryParam);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询产品对应仓库数量", notes = "查询")
    @GetMapping ("/selectAll")
    public JsonResult<List<WarehouseFactoryAdministrationVO>> selectAll(String productId){
            JsonResult jsonResult = new JsonResult();
            List<WarehouseFactoryAdministrationVO> warehouseFactoryAdministrationVOS = warehouseService.selectAll(productId);
            if (CollectionUtils.isNotEmpty(warehouseFactoryAdministrationVOS)){
                return  JsonResult.success("请求成功",warehouseFactoryAdministrationVOS);
            }else {
                return  JsonResult.success("数据为空",warehouseFactoryAdministrationVOS);
            }
    }


    @ApiOperation(value = "添加仓库", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(WarehouseFactoryAdministrationForm warehouseFactoryAdministrationForm) {
        if (warehouseService.add(warehouseFactoryAdministrationForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "添加仓库", notes = "添加")
    @PostMapping("/addByWarehouse")
    public JsonResult addByWarehouse(@RequestBody WarehouseFactoryAdministrationForm warehouseFactoryAdministrationForm) {
        WrehouseFactoryAdministrationEntity warehouse = new WrehouseFactoryAdministrationEntity();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(Warehouse.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseFactoryAdministrationForm, warehouse, copyOptions);
        warehouseService.save(warehouse);
        return JsonResult.success(warehouse.id);
    }


    @ApiOperation(value = "修改仓库", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(WarehouseFactoryAdministrationForm warehouseFactoryAdministrationForm) {
        WrehouseFactoryAdministrationEntity warehouse = warehouseService.getById(warehouseFactoryAdministrationForm.getId());
        if (warehouse == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WrehouseFactoryAdministrationEntity.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseFactoryAdministrationForm, warehouse, copyOptions);
        if (warehouseService.updateById(warehouse)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除仓库", notes = "删除")
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long warehouseId) {
        if (warehouseService.removeById(warehouseId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "检查唯一性")
    @GetMapping("/isOnly")
    public JsonResult isOnly(@RequestParam(name = "code", required = false) String code, @RequestParam(name = "name", required = false) String name, @RequestParam(name = "id", required = false) Long id) {
        QueryWrapper<WrehouseFactoryAdministrationEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.eq("code", code);
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.eq("name", name);
        }
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        int count = warehouseService.count(queryWrapper);
        return JsonResult.success(count == 0);
    }

    @ApiOperation(value = "查询企业端仓库", notes = "查询")
    @GetMapping("/getWarehouseVOAll")
    public JsonResult getWarehouseVOAll() {
        QueryWrapper<WrehouseFactoryAdministrationEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        List<WrehouseFactoryAdministrationEntity> list = warehouseService.list(wrapper);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "查询平台端仓库", notes = "查询")
    @GetMapping("/getPlatformWarehouseAll")
    public JsonResult<List<com.wing.platform.order.model.entity.Warehouse>> getPlatformWarehouseAll(@RequestParam(name = "province", required = false) Long province, @RequestParam(name = "city", required = false) Long city) {
        JsonResult<List<com.wing.platform.order.model.entity.Warehouse>> jsonResult = platformClient.getPlatformWarehouseAll(province, city);
        return JsonResult.success(jsonResult.getData());
    }


    @ApiOperation(value = "查询产品对应仓库数量", notes = "查询")
    @GetMapping ("/findFactoryInfo")
    public JsonResult findFactoryInfo(Long id){
        WarehouseFactoryAdministrationVO warehouseFactoryAdministrationVO = warehouseService.findFactoryInfo(id);
        warehouseFactoryAdministrationVO.setWarehouseFactoryShelfSpaceVOList(warehouseService.findFactoryShelfSpace(id.toString()));
      return JsonResult.success(warehouseFactoryAdministrationVO);
    }

    @ApiOperation(value = "根据库区找库位", notes = "查询")
    @GetMapping ("/findFactoryShelfSpaceByWarehouseAreaId")
    public JsonResult findFactoryShelfSpaceByWarehouseAreaId(Long id){
        List<WarehouseFactoryAdministrationVO> warehouseFactoryAdministrationVOList = warehouseService.findFactoryShelfSpaceByWarehouseAreaId(id);
        return JsonResult.success(warehouseFactoryAdministrationVOList);
    }

    @ApiOperation(value = "根据库位找货架", notes = "查询")
    @GetMapping ("/findFactoryShelfByShelId")
    public JsonResult findFactoryShelfByShelId(Long id){
        WarehouseFactoryShelfSpaceVO warehouseFactoryAdministrationVO = warehouseService.findFactoryShelfByShelId(id);
        return JsonResult.success(warehouseFactoryAdministrationVO);
    }


    @ApiOperation(value = "根据企业id查仓库", notes = "查询")
    @GetMapping ("/findByContract")
    public JsonResult findByContract(Long id){
        List<WrehouseFactoryAdministrationEntity> wrehouseFactoryAdministrationEntityList = warehouseService.findByContract(id);
        return JsonResult.success(wrehouseFactoryAdministrationEntityList);
    }


}
